<template>
  <div class="auth-container">
    <div class="auth-card">
      <div class="auth-header">
        <h1 class="auth-title">EduMaster</h1>
        <p class="auth-subtitle">个人学习信息系统</p>
      </div>

      <n-tabs 
        v-model:value="activeTab" 
        type="segment" 
        animated
        class="auth-tabs"
      >
        <n-tab-pane name="login" tab="登录">
          <n-form
            ref="loginFormRef"
            :model="loginForm"
            :rules="loginRules"
            size="large"
            class="auth-form"
          >
            <n-form-item path="email" label="邮箱">
              <n-input
                v-model:value="loginForm.email"
                type="text"
                placeholder="请输入邮箱地址"
                :input-props="{ autocomplete: 'email' }"
              >
                <template #prefix>
                  <n-icon :component="Mail" />
                </template>
              </n-input>
            </n-form-item>

            <n-form-item path="password" label="密码">
              <n-input
                v-model:value="loginForm.password"
                type="password"
                placeholder="请输入密码"
                show-password-on="mousedown"
                :input-props="{ autocomplete: 'current-password' }"
                @keydown.enter="handleLogin"
              >
                <template #prefix>
                  <n-icon :component="Lock" />
                </template>
              </n-input>
            </n-form-item>

            <n-form-item>
              <div class="auth-options">
                <n-checkbox v-model:checked="rememberMe">
                  记住我
                </n-checkbox>
              </div>
            </n-form-item>

            <n-form-item>
              <n-button
                type="primary"
                size="large"
                block
                :loading="authStore.isLoading"
                @click="handleLogin"
              >
                登录
              </n-button>
            </n-form-item>
          </n-form>
        </n-tab-pane>

        <n-tab-pane name="register" tab="注册">
          <n-form
            ref="registerFormRef"
            :model="registerForm"
            :rules="registerRules"
            size="large"
            class="auth-form"
          >
            <n-form-item path="username" label="用户名">
              <n-input
                v-model:value="registerForm.username"
                placeholder="请输入用户名"
                :input-props="{ autocomplete: 'username' }"
              >
                <template #prefix>
                  <n-icon :component="User" />
                </template>
              </n-input>
            </n-form-item>

            <n-form-item path="email" label="邮箱">
              <n-input
                v-model:value="registerForm.email"
                type="text"
                placeholder="请输入邮箱地址"
                :input-props="{ autocomplete: 'email' }"
              >
                <template #prefix>
                  <n-icon :component="Mail" />
                </template>
              </n-input>
            </n-form-item>

            <n-form-item path="password" label="密码">
              <n-input
                v-model:value="registerForm.password"
                type="password"
                placeholder="请输入密码（至少8位）"
                show-password-on="mousedown"
                :input-props="{ autocomplete: 'new-password' }"
              >
                <template #prefix>
                  <n-icon :component="Lock" />
                </template>
              </n-input>
              <template #feedback>
                <div class="password-strength">
                  <div class="strength-bar">
                    <div 
                      class="strength-fill"
                      :class="`strength-${passwordStrength}`"
                      :style="{ width: `${(passwordStrength / 4) * 100}%` }"
                    ></div>
                  </div>
                  <span class="strength-text">{{ getPasswordStrengthText() }}</span>
                </div>
              </template>
            </n-form-item>

            <n-form-item path="confirmPassword" label="确认密码">
              <n-input
                v-model:value="registerForm.confirmPassword"
                type="password"
                placeholder="请再次输入密码"
                show-password-on="mousedown"
                :input-props="{ autocomplete: 'new-password' }"
                @keydown.enter="handleRegister"
              >
                <template #prefix>
                  <n-icon :component="Lock" />
                </template>
              </n-input>
            </n-form-item>

            <n-form-item>
              <n-button
                type="primary"
                size="large"
                block
                :loading="authStore.isLoading"
                @click="handleRegister"
              >
                注册
              </n-button>
            </n-form-item>
          </n-form>
        </n-tab-pane>
      </n-tabs>
    </div>

    <!-- 背景装饰 -->
    <div class="auth-background">
      <div class="bg-shape bg-shape-1"></div>
      <div class="bg-shape bg-shape-2"></div>
      <div class="bg-shape bg-shape-3"></div>
      
      <!-- 动态颗粒背景 -->
      <div v-if="activeTab === 'register'" class="particles-container">
        <div 
          v-for="particle in particles" 
          :key="particle.id"
          class="particle"
          :style="{
            left: particle.x + 'px',
            top: particle.y + 'px',
            animationDelay: particle.delay + 's',
            animationDuration: particle.duration + 's'
          }"
        ></div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { 
  NTabs, 
  NTabPane, 
  NForm, 
  NFormItem, 
  NInput, 
  NButton, 
  NCheckbox,
  NIcon,
  useMessage,
  type FormInst,
  type FormRules
} from 'naive-ui'
import { Mail, Lock, User } from '@vicons/tabler'
import { useAuthStore } from '@/stores/auth'
import { getPasswordStrength, isValidEmail } from '@/utils'

const router = useRouter()
const message = useMessage()
const authStore = useAuthStore()

// 表单引用
const loginFormRef = ref<FormInst | null>(null)
const registerFormRef = ref<FormInst | null>(null)

// 当前选项卡
const activeTab = ref('login')

// 记住我
const rememberMe = ref(false)

// 登录表单
const loginForm = ref({
  email: '',
  password: ''
})

// 注册表单
const registerForm = ref({
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
})

// 密码强度
const passwordStrength = computed(() => {
  return getPasswordStrength(registerForm.value.password)
})

// 颗粒动画
interface Particle {
  id: number
  x: number
  y: number
  delay: number
  duration: number
}

const particles = ref<Particle[]>([])
let particleAnimationId: number | null = null

// 生成颗粒
const generateParticles = () => {
  const particleCount = 50
  const newParticles: Particle[] = []
  
  for (let i = 0; i < particleCount; i++) {
    newParticles.push({
      id: i,
      x: Math.random() * window.innerWidth,
      y: Math.random() * window.innerHeight,
      delay: Math.random() * 5,
      duration: 3 + Math.random() * 4
    })
  }
  
  particles.value = newParticles
}

// 更新颗粒位置
const updateParticles = () => {
  particles.value = particles.value.map(particle => ({
    ...particle,
    x: Math.random() * window.innerWidth,
    y: Math.random() * window.innerHeight
  }))
  
  particleAnimationId = setTimeout(updateParticles, 5000)
}

// 获取密码强度文本
const getPasswordStrengthText = () => {
  const strength = passwordStrength.value
  const texts = ['很弱', '弱', '一般', '强', '很强']
  return texts[strength] || '很弱'
}

// 登录表单验证规则
const loginRules: FormRules = {
  email: [
    {
      required: true,
      message: '请输入邮箱地址',
      trigger: ['input', 'blur']
    },
    {
      validator: (_rule, value) => {
        if (value && !isValidEmail(value)) {
          return new Error('请输入有效的邮箱地址')
        }
        return true
      },
      trigger: ['input', 'blur']
    }
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: ['input', 'blur']
    }
  ]
}

// 注册表单验证规则
const registerRules: FormRules = {
  username: [
    {
      required: true,
      message: '请输入用户名',
      trigger: ['input', 'blur']
    },
    {
      min: 2,
      max: 20,
      message: '用户名长度应在2-20个字符之间',
      trigger: ['input', 'blur']
    }
  ],
  email: [
    {
      required: true,
      message: '请输入邮箱地址',
      trigger: ['input', 'blur']
    },
    {
      validator: (_rule, value) => {
        if (value && !isValidEmail(value)) {
          return new Error('请输入有效的邮箱地址')
        }
        return true
      },
      trigger: ['input', 'blur']
    }
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: ['input', 'blur']
    },
    {
      min: 8,
      message: '密码长度至少8位',
      trigger: ['input', 'blur']
    }
  ],
  confirmPassword: [
    {
      required: true,
      message: '请确认密码',
      trigger: ['input', 'blur']
    },
    {
      validator: (_rule, value) => {
        if (value && value !== registerForm.value.password) {
          return new Error('两次输入的密码不一致')
        }
        return true
      },
      trigger: ['input', 'blur']
    }
  ]
}

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    await loginFormRef.value.validate()
    
    const result = await authStore.login({
      email: loginForm.value.email,
      password: loginForm.value.password
    })
    
    if (result.success) {
      message.success('登录成功！')
      // 跳转到仪表盘
      router.push('/dashboard')
    } else {
      message.error(result.message || '登录失败')
    }
  } catch (error: any) {
    if (error?.message) {
      message.error(error.message)
    } else {
      console.error('Login validation failed:', error)
    }
  }
}

// 处理注册
const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  try {
    await registerFormRef.value.validate()
    
    const result = await authStore.register({
      username: registerForm.value.username,
      email: registerForm.value.email,
      password: registerForm.value.password
    })
    
    if (result.success) {
      message.success('注册成功！')
      // 跳转到仪表盘
      router.push('/dashboard')
    } else {
      message.error(result.message || '注册失败')
    }
  } catch (error: any) {
    if (error?.message) {
      message.error(error.message)
    } else {
      console.error('Register validation failed:', error)
    }
  }
}

// 监听密码变化，重新验证确认密码
watch(
  () => registerForm.value.password,
  () => {
    if (registerForm.value.confirmPassword) {
      registerFormRef.value?.validate()
    }
  }
)

// 监听选项卡变化，控制颗粒动画
watch(activeTab, (newTab) => {
  if (newTab === 'register') {
    generateParticles()
    updateParticles()
  } else {
    if (particleAnimationId) {
      clearTimeout(particleAnimationId)
      particleAnimationId = null
    }
  }
})

// 组件挂载时初始化
onMounted(() => {
  if (activeTab.value === 'register') {
    generateParticles()
    updateParticles()
  }
})

// 组件卸载时清理
onUnmounted(() => {
  if (particleAnimationId) {
    clearTimeout(particleAnimationId)
  }
})
</script>

<style scoped>
.auth-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  position: relative;
  overflow: hidden;
}

.auth-card {
  width: 100%;
  max-width: 400px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 40px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 1;
}

.auth-header {
  text-align: center;
  margin-bottom: 32px;
}

.auth-title {
  font-size: 32px;
  font-weight: 700;
  color: #2c3e50;
  margin: 0 0 8px 0;
  background: linear-gradient(135deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.auth-subtitle {
  font-size: 14px;
  color: #64748b;
  margin: 0;
}

.auth-tabs {
  margin-bottom: 24px;
}

.auth-form {
  margin-top: 24px;
}

.auth-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.password-strength {
  margin-top: 8px;
}

.strength-bar {
  height: 4px;
  background: #f1f5f9;
  border-radius: 2px;
  overflow: hidden;
  margin-bottom: 4px;
}

.strength-fill {
  height: 100%;
  transition: all 0.3s ease;
  border-radius: 2px;
}

.strength-fill.strength-0,
.strength-fill.strength-1 {
  background: #ef4444;
}

.strength-fill.strength-2 {
  background: #f59e0b;
}

.strength-fill.strength-3 {
  background: #10b981;
}

.strength-fill.strength-4 {
  background: #059669;
}

.strength-text {
  font-size: 12px;
  color: #64748b;
}

.auth-background {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
}

.bg-shape {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 6s ease-in-out infinite;
}

.bg-shape-1 {
  width: 200px;
  height: 200px;
  top: 10%;
  left: 10%;
  animation-delay: 0s;
}

.bg-shape-2 {
  width: 150px;
  height: 150px;
  top: 60%;
  right: 10%;
  animation-delay: 2s;
}

.bg-shape-3 {
  width: 100px;
  height: 100px;
  bottom: 20%;
  left: 20%;
  animation-delay: 4s;
}

/* 颗粒动画样式 */
.particles-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  overflow: hidden;
}

.particle {
  position: absolute;
  width: 4px;
  height: 4px;
  background: rgba(255, 255, 255, 0.6);
  border-radius: 50%;
  animation: particleFloat linear infinite;
  box-shadow: 0 0 6px rgba(255, 255, 255, 0.3);
}

.particle:nth-child(2n) {
  width: 3px;
  height: 3px;
  background: rgba(255, 255, 255, 0.4);
}

.particle:nth-child(3n) {
  width: 2px;
  height: 2px;
  background: rgba(255, 255, 255, 0.8);
}

.particle:nth-child(4n) {
  width: 5px;
  height: 5px;
  background: rgba(255, 255, 255, 0.3);
}

.particle:nth-child(5n) {
  background: rgba(103, 126, 234, 0.6);
}

.particle:nth-child(7n) {
  background: rgba(118, 75, 162, 0.6);
}

@keyframes particleFloat {
  0% {
    transform: translateY(100vh) translateX(0) rotate(0deg);
    opacity: 0;
  }
  10% {
    opacity: 1;
  }
  90% {
    opacity: 1;
  }
  100% {
    transform: translateY(-100px) translateX(100px) rotate(360deg);
    opacity: 0;
  }
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px) rotate(0deg);
  }
  50% {
    transform: translateY(-20px) rotate(180deg);
  }
}

/* 响应式设计 */
@media (max-width: 480px) {
  .auth-card {
    padding: 24px;
    margin: 16px;
  }
  
  .auth-title {
    font-size: 28px;
  }
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .auth-card {
    background: rgba(30, 30, 30, 0.95);
    color: #f8fafc;
  }
  
  .auth-title {
    color: #f8fafc;
  }
  
  .auth-subtitle {
    color: #94a3b8;
  }
  
  .strength-text {
    color: #94a3b8;
  }
}
</style>